package dao.Implementation;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import Donnees.Nature;
import Util.HibernateUtil;
import dao.Interfaces.INatureDAO;

public class NatureDAO implements INatureDAO {
	
	public NatureDAO() {
	}
	
	public List<Nature> selectAll() {
		List<Nature> listeNature = new ArrayList<Nature>();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		listeNature.addAll(session.createQuery("from Nature").list());

		session.flush();
		tx.commit();
		session.close();

		return listeNature;
	}

	public long insert(Nature f) {
		Nature natureTemp = f;
		Long msgId;

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		msgId = (Long) session.save(natureTemp);

		session.flush();
		tx.commit();
		session.close();
		
		return msgId;
	}
	
	public int delete(Nature f) {
		Nature natureTemp = f;
		int retour;
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		
		retour = session.createQuery("delete from Nature where id='" + natureTemp.getId() + "'").executeUpdate();

		session.flush();
		tx.commit();
		session.close();
		
		return retour;
	}
	
	public Nature getById(long id) {
		Nature natureTemp = new Nature();

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		natureTemp = (Nature) session.createQuery("from Nature where id='" + id + "'").list().get(0);

		session.flush();
		tx.commit();
		session.close();

		return natureTemp;
	}
}
